package pl.vm.domain;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pl.vm.domain.interfaces.Classification;
import pl.vm.domain.interfaces.Round;
import pl.vm.domain.simulator.PointsCalculator;
import pl.vm.domain.simulator.SimplePointsCalculator;

public class RoundClassification implements Classification {

	private Round round;
	private Map<VirtualTeam, Double> teamPoints = new HashMap<>();
	private List<VirtualTeam> classification = new ArrayList<VirtualTeam>();
	private PointsCalculator calculator = new SimplePointsCalculator();

	public RoundClassification(Round round) {
		this.round = round;
	}

	public RoundClassification(RoundClassification classification) {
		this.teamPoints.putAll(classification.teamPoints);
		this.classification.addAll(classification.classification);
		this.round = classification.round;
	}
	
	public void calculateTeamPoints() {
		for (VirtualTeam team : round.getTeams()) {
			if (team.isValid()) {
				teamPoints.put(team,
					calculator.calculateTeamPointsInRound(team, round));
			}
		}
	}

	public void calculateClassification() {
		classification.addAll(teamPoints.keySet());
		Collections.sort(classification, new ValueComparator(teamPoints));
	}

	public double getTeamPoints(VirtualTeam team) {
		return teamPoints.get(team);
	}
	
	@Override
	public List<VirtualTeam> getClassification() {
		return classification;
	}

	@Override
	public void addPointsForTeam(VirtualTeam team, double pointsToAdd) {
		double newPoints = teamPoints.get(team) + pointsToAdd;
		teamPoints.put(team, newPoints);
	}
	
	@Override
	public void substractPointForTeam(VirtualTeam team, double pointsToSubstract) {
		double newPoints = teamPoints.get(team) - pointsToSubstract;
		teamPoints.put(team, newPoints);
	}	
}
